package edu.nyu.hps.architecture;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(args.length<4){
			System.out.println("Usage: \"java -jar Server.jar <port> <cat_x> <cat_y> <mouse_x> <mouse_y> \" ");
			System.exit(1);
		}
		ServerSocket serverSocket = null;
		int port = 4441, catX, catY, mouseX, mouseY;
		boolean listening = true;

		port = Integer.parseInt(args[0]);
		try {
			serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			System.err.println("Could not listen on port: " + port);
			System.exit(-1);
		}
		catX = Integer.parseInt(args[1]);
		catY = Integer.parseInt(args[2]);
		mouseX = Integer.parseInt(args[3]);
		mouseY = Integer.parseInt(args[4]);

		Player cat = new Cat(catX, catY);
		Player mouse = new Mouse(mouseX, mouseY);
		System.out.println("New Game has begun");
		System.out.println("Start the interface");
		Socket socket1 = null;
		try {
			socket1 = serverSocket.accept();
		} catch (IOException e1) {
			System.out.println("Could not connect to the interface");
		}
		Thread appletThread = new AppletThread(socket1,mouse,cat);
		
		//Start the server once
		while (listening)
			try {
				System.out.println("Let cat connect");
				ClientThread catT = new ClientThread(serverSocket.accept(), cat, mouse);
				catT.start();
				
				System.out.println("Let mouse connect");
				ClientThread mouseT = new ClientThread(serverSocket.accept(), mouse, cat);
				mouseT.start();
				
				appletThread.run();
				try {
					catT.join();
					mouseT.join();
					
				} catch (InterruptedException e) {
					System.out.println("Could not close the threads");
				}
				cat = new Cat(catX,catY);
				mouse = new Mouse(mouseX,mouseY);
				appletThread = new AppletThread(socket1,mouse,cat);
				
//				System.out.println("Watch the show!");
			} catch (IOException e) {
				System.out
						.println("Could not create a thread for the incoming client");
			}

		try {
			serverSocket.close();
		} catch (IOException e) {
			System.out.println("Could not close the server");
		}
	}
}
